<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of AssetManage
 *
 * @author gensen
 */
class AssetManage extends CI_Controller{
    private $appId;
    private $appSecret;
    //put your code here
    function __construct() {
        parent::__construct();
        date_default_timezone_set('Asia/Shanghai'); 
        $this->appId = "wxd2b4ceb62757c00c";
        $this->appSecret = "rLIQWiwWU82MGUcLEgGHlIQKox_0YrCNUPsXRPudFec";
    }
    
    function index(){
        $year = date("Y");
        $month = date("m");
        $jsapiTicket = $this->getJsApiTicket();
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $timestamp = time();
        $nonceStr = $this->createNonceStr();
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
        $signature = sha1($string);
        $signPackage = array(
            "appId"     => $this->appId,
            "nonceStr"  => $nonceStr,
            "timestamp" => $timestamp,
            "url"       => $url,
            "signature" => $signature,
            "year"      => $year,
            "month"     => $month,
            "type"      => "search"
        );
        //var_dump($signPackage);
        $this->load->view("AssetManage",$signPackage);
    }
    private function getAssetInfo(){
        $BUKRS = $_REQUEST['BUKRS'];
        $ANLN1_LOW = $_REQUEST['ANLN1_LOW'];
        $api = $_REQUEST['api'];
    }
    
    function saveAsset(){
        $CREATETIME = date("Y-m-d H:i:s");
        $data = array(
            "ANLN1" => $_POST["ANLN1"],
            "TXT50" => $_POST["TXT50"],
            "TXA50" => $_POST["TXA50"],
            "ANLKL" => $_POST["ANLKL"],
            "TXK20" => $_POST["TXK20"],
            "BUKRS" => $_POST["BUKRS"],
            "KOSTL" => $_POST["KOSTL"],
            "KTEXT" => $_POST["KTEXT"],
            "ZUGDT" => $_POST["ZUGDT"],
            "CREATETIME" => $CREATETIME,
        );
        $this->Data_model->add_data_Oracle($data,"ASSETMANAGE");
    }

    private function getJsApiTicket() {
        // jsapi_ticket 应该全局存储与更新，以下代码以写入到文件中做示例
        //$data = json_decode(file_get_contents("weixinJS/jsapi_ticket.json"));
        $data = $this->Data_model->get_single_data(array('type' => 'jsapi_ticket'),"WEIXININFOZJ");
        if ($data['time'] < time()) {
            $accessToken = $this->get_access_token();
            // 如果是企业号用以下 URL 获取 ticket
            $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
            //$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
            $res = json_decode($this->http_request_json($url));
            $ticket = $res->ticket;
            if ($ticket) {
                $this->Data_model->update_data(array('type' => 'jsapi_ticket'),array('time' => time() + 7000,'jsapi_ticket' => $ticket),"WEIXININFOZJ");
            }
        } else {
            $ticket = $data['jsapi_ticket'];
        }
        return $ticket;
    }
    
    function get_access_token(){
        $result = $this->Data_model->get_single_data(array('name'=>'中骏森驰',
                                                            'type'=>'AssetManage'),"WEIXININFOZJ");
        if($result['time'] < time()){
            $corpid = $result['corpid'];
            $corpsecret = $result['corpsecret'];
            $url="https://qyapi.weixin.qq.com/cgi-bin/gettoken?&corpid=".$corpid."&corpsecret=".$corpsecret;
            $json=self::http_request_json($url);//这个地方不能用file_get_contents
            $data=json_decode($json,true);
            if(isset($data['access_token'])){
                $this->Data_model->update_data(array('name'=>'中骏森驰',
                                                                'type'=>'AssetManage'),array('access_token' => $data['access_token'],'time' => time()+7100),'WEIXININFOZJ');
            
                $access_token = $data['access_token'];
            }else{
                return "获取access_token错误";
            } 
        }else{
            $access_token = $result['access_token'];
        }
        return $access_token;
    }
    
    //因为url是https 所有请求不能用file_get_contents,用curl请求json 数据
    function http_request_json($url){  
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;  
    }
    
    private function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
          $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
    
    private function getAssetArr($BUKRS="",$ANLN1_LOW="",$ANLN1_HIGH="",$ANLKL_LOW="",$ANLKL_HIGH="",$KOSTL_LOW="",$KOSTL_HIGH="",$ERDAT_LOW="",$ERDAT_HIGH="",$api=""){
        $year        = date("Y");
        $month       = date("m");
        $url = "http://oaweixin.gensenauto.com/zxbpm/App_API_Server.nsf/$api?openagent";
        $post = array(
            "year"        => $year,
            "month"       => $month,
            "BUKRS"       => $BUKRS,
            "ANLN1_LOW"   => $ANLN1_LOW,
            "ANLN1_HIGH"  => $ANLN1_HIGH,
            "ANLKL_LOW"   => $ANLKL_LOW,
            "ANLKL_HIGH"  => $ANLKL_HIGH,
            "KOSTL_LOW"   => $KOSTL_LOW,
            "KOSTL_HIGH"  => $KOSTL_HIGH,
            "ERDAT_LOW"   => $ERDAT_LOW,
            "ERDAT_HIGH"  => $ERDAT_HIGH,
        );
        return $this->curl_request($url,$post);
    }
    function test(){
        $ANLN1_LOW = "324215";
        $res = $this->Data_model->get_single_data(array("FID" => $ANLN1_LOW),"C21POOL");
        if(isset($res)){
            echo '1'; 
        }else{
            echo '2';
        }
    }
    
    function getAssetJson(){
        $year        = date("Y");
        $month       = date("m");
        
        $data = $_POST;
        $BUKRS       = $data['BUKRS'];
        $ANLN1_LOW   = $data['ANLN1_LOW'];
        $ANLN1_HIGH  = $data['ANLN1_HIGH'];
        $ANLKL_LOW   = $data['ANLKL_LOW'];
        $ANLKL_HIGH  = $data['ANLKL_HIGH'];
        $KOSTL_LOW   = $data['KOSTL_LOW'];
        $KOSTL_HIGH  = $data['KOSTL_HIGH'];
        $ERDAT_LOW   = $data['ERDAT_LOW'];
        $ERDAT_HIGH  = $data['ERDAT_HIGH'];
        $api         = $data['api'];
        /*
        $BUKRS       = $_POST['BUKRS'];
        $ANLN1_LOW   = $_POST['ANLN1_LOW'];
        $ANLN1_HIGH  = $_POST['ANLN1_HIGH'];
        $ANLKL_LOW   = $_POST['ANLKL_LOW'];
        $ANLKL_HIGH  = $_POST['ANLKL_HIGH'];
        $KOSTL_LOW   = $_POST['KOSTL_LOW'];
        $KOSTL_HIGH  = $_POST['KOSTL_HIGH'];
        $ERDAT_LOW   = $_POST['ERDAT_LOW'];
        $ERDAT_HIGH  = $_POST['ERDAT_HIGH'];
        $api         = $_POST['api'];
         * 
         */
        
        $return_data = array();
        $oracle_data = $this->Data_model->get_single_data(array("ANLN1" => $ANLN1_LOW,"BUKRS" => $BUKRS),"ASSETMANAGE");
        if(!empty($oracle_data)){
            $oracle_data['datatype'] = "oracle";
            $return_data = array(
                "data" => array("0" => $oracle_data),
                "iserror" => "0",
                "msg"     => "数据查询成功！"
            );
        }else{
            $url = "http://oaweixin.gensenauto.com/zxbpm/App_API_Server.nsf/$api?openagent";
            $post = array(
                "year"        => $year,
                "month"       => $month,
                "BUKRS"       => $BUKRS,
                "ANLN1_LOW"   => $ANLN1_LOW,
                "ANLN1_HIGH"  => $ANLN1_HIGH,
                "ANLKL_LOW"   => $ANLKL_LOW,
                "ANLKL_HIGH"  => $ANLKL_HIGH,
                "KOSTL_LOW"   => $KOSTL_LOW,
                "KOSTL_HIGH"  => $KOSTL_HIGH,
                "ERDAT_LOW"   => $ERDAT_LOW,
                "ERDAT_HIGH"  => $ERDAT_HIGH,
            );
            $return_data = json_decode($this->curl_request($url,$post),true);
            $return_data['datatype'] = "SAP";
        }
        echo json_encode($return_data);
        
    }
    //参数1：访问的URL，参数2：post数据(不填则为GET)，参数3：提交的$cookies,参数4：是否返回$cookies
    private function curl_request($url,$post='',$cookie='', $returnCookie=0){
           $curl = curl_init();
           curl_setopt($curl, CURLOPT_URL, $url);
           curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)');
           curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
           curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
           curl_setopt($curl, CURLOPT_REFERER, "http://XXX");
           if($post) {
               curl_setopt($curl, CURLOPT_POST, 1);
               curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post));
           }
           if($cookie) {
               curl_setopt($curl, CURLOPT_COOKIE, $cookie);
           }
           curl_setopt($curl, CURLOPT_HEADER, $returnCookie);
           curl_setopt($curl, CURLOPT_TIMEOUT, 10);
           curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
           $data = curl_exec($curl);
           if (curl_errno($curl)) {
               return curl_error($curl);
           }
           curl_close($curl);
           if($returnCookie){
               list($header, $body) = explode("\r\n\r\n", $data, 2);
               preg_match_all("/Set\-Cookie:([^;]*);/", $header, $matches);
               $info['cookie']  = substr($matches[1][0], 1);
               $info['content'] = $body;
               return $info;
           }else{
               return $data;
           }
    }
    
    //判断查询资产是否已经录入系统
    public function isAssetExist(){
        $ANLN1 = $_REQUEST['ANLN1'];
        $this->Data_model->get_single_data(array('ANLN1'=>$ANLN1),'');
    }


    //新增资产录入关系型数据库
    public function addAsset(){
        $get_data = array(
            'ANLN1' => $_REQUEST['ANLN1'],
            'TXT50' => $_REQUEST['TXT50'],
            'TXA50' => $_REQUEST['TXA50'],
            'ANLKL' => $_REQUEST['ANLKL'],
            'TXK20' => $_REQUEST['TXK20'],
            'BUKRS' => $_REQUEST['BUKRS'],
            'KOSTL' => $_REQUEST['KOSTL'],
            'KOSTL' => $_REQUEST['KOSTL'],
            'ZUGDT' => $_REQUEST['ZUGDT']
         );
        $this->Data_model->add_data_Oracle($get_data,'ASSETMANAGE');
    }
    function testpost(){
        $data = array(
            'BUKRS' => $_REQUEST['BUKRS'],
            'ANLN1_LOW' => $_REQUEST['ANLN1_LOW']
        );
        echo json_encode($data);
    }
   
}
